﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace ServerNetworkPressure
{
    public class ServerAction
    {
        private TcpListener listion;
        private int clientcount = 0;
        public ServerAction()
        {
            Thread log = new Thread(() => LogData());
            log.Start();
        }

        public void OpenPort()
        {
            var ipaddres = IPAddress.Parse("10.0.2.40");
            listion = new TcpListener(ipaddres, 12345);
            listion.Start();
            Thread listionth = new Thread(() => Listion());
            listionth.Start();
            Console.WriteLine("启动监听~");
        }

        private void Listion()
        {
            while (true)
            {
                try
                {
                    var client = listion.AcceptSocket();
                    clientcount++;
                    Thread eclient = new Thread(() => EveryClient(client));
                    eclient.Start();
                    Console.WriteLine("新增一个客户端接入！");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }

        private void EveryClient(Socket socket)
        {
            while (true)
            {
                try
                {
                    int size = socket.Available;
                    if (size > 0)
                    {
                        Console.WriteLine("收到一次数据包！");
                        byte[] buffer = new byte[size];
                        socket.Receive(buffer);
                        socket.Send(buffer);
                        Console.WriteLine("返回一次数据包！");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }

        private void LogData()
        {
            while (true)
            {
                Thread.Sleep(1000*60);
                System.IO.File.AppendAllText(Environment.CurrentDirectory+"/pressure.log", clientcount.ToString() + "\r\n");
            }
        }
    }
}
